/**
 * 模块存储实现 - 基于内存的缓存系统
 */
import type { IModuleStorage, ModuleCacheEntry } from './types'

export class ModuleStorage implements IModuleStorage {
  private cache = new Map<string, ModuleCacheEntry>()
  private cleanupInterval: number | null = null
  private readonly DEFAULT_TTL = 30 * 60 * 1000 // 30分钟默认过期时间

  constructor() {
    // 启动定时清理任务
    this.startCleanupTask()
  }

  /**
   * 保存模块数据到缓存
   */
  async save(key: string, data: any, ttl: number = this.DEFAULT_TTL): Promise<void> {
    const now = Date.now()
    const entry: ModuleCacheEntry = {
      moduleId: key,
      content: data,
      cachedAt: now,
      expiresAt: now + ttl,
      cacheKey: this.generateCacheKey(key, data)
    }

    this.cache.set(key, entry)
    
    // 触发缓存事件
    this.emitCacheEvent('cache:saved', key, entry)
  }

  /**
   * 从缓存获取模块数据
   */
  async get(key: string): Promise<any> {
    const entry = this.cache.get(key)
    
    if (!entry) {
      return null
    }

    // 检查是否过期
    if (Date.now() > entry.expiresAt) {
      this.cache.delete(key)
      this.emitCacheEvent('cache:expired', key, entry)
      return null
    }

    this.emitCacheEvent('cache:hit', key, entry)
    return entry.content
  }

  /**
   * 从缓存删除模块数据
   */
  async delete(key: string): Promise<void> {
    const entry = this.cache.get(key)
    if (entry) {
      this.cache.delete(key)
      this.emitCacheEvent('cache:deleted', key, entry)
    }
  }

  /**
   * 清理过期数据
   */
  async cleanup(): Promise<void> {
    const now = Date.now()
    const expiredKeys: string[] = []

    this.cache.forEach((entry, key) => {
      if (now > entry.expiresAt) {
        expiredKeys.push(key)
      }
    })

    expiredKeys.forEach(key => {
      const entry = this.cache.get(key)!
      this.cache.delete(key)
      this.emitCacheEvent('cache:expired', key, entry)
    })

    if (expiredKeys.length > 0) {
      console.log(`[ModuleStorage] Cleaned up ${expiredKeys.length} expired cache entries`)
    }
  }

  /**
   * 获取缓存统计信息
   */
  getStats() {
    const now = Date.now()
    let totalSize = 0
    let expiredCount = 0
    let activeCount = 0

    this.cache.forEach(entry => {
      // 估算缓存大小
      totalSize += JSON.stringify(entry.content).length
      
      if (now > entry.expiresAt) {
        expiredCount++
      } else {
        activeCount++
      }
    })

    return {
      totalEntries: this.cache.size,
      activeEntries: activeCount,
      expiredEntries: expiredCount,
      estimatedSizeBytes: totalSize,
      hitRate: this.calculateHitRate()
    }
  }

  /**
   * 清空所有缓存
   */
  async clear(): Promise<void> {
    const size = this.cache.size
    this.cache.clear()
    console.log(`[ModuleStorage] Cleared ${size} cache entries`)
    this.emitCacheEvent('cache:cleared', null, null)
  }

  /**
   * 检查缓存中是否存在指定键
   */
  has(key: string): boolean {
    const entry = this.cache.get(key)
    if (!entry) {
      return false
    }

    // 检查是否过期
    if (Date.now() > entry.expiresAt) {
      this.cache.delete(key)
      return false
    }

    return true
  }

  /**
   * 获取缓存条目信息
   */
  getCacheEntry(key: string): ModuleCacheEntry | undefined {
    return this.cache.get(key)
  }

  /**
   * 获取所有缓存键
   */
  keys(): string[] {
    return Array.from(this.cache.keys())
  }

  /**
   * 获取所有缓存值
   */
  values(): ModuleCacheEntry[] {
    return Array.from(this.cache.values())
  }

  /**
   * 设置缓存过期时间
   */
  async setExpiry(key: string, ttl: number): Promise<void> {
    const entry = this.cache.get(key)
    if (entry) {
      entry.expiresAt = Date.now() + ttl
      this.emitCacheEvent('cache:expiry-updated', key, entry)
    }
  }

  /**
   * 销毁存储实例
   */
  destroy(): void {
    if (this.cleanupInterval) {
      clearInterval(this.cleanupInterval)
      this.cleanupInterval = null
    }
    this.cache.clear()
  }

  /**
   * 启动定时清理任务
   */
  private startCleanupTask(): void {
    // 每5分钟清理一次过期缓存
    this.cleanupInterval = window.setInterval(() => {
      this.cleanup().catch(error => {
        console.error('[ModuleStorage] Error during cleanup:', error)
      })
    }, 5 * 60 * 1000)
  }

  /**
   * 生成缓存键
   */
  private generateCacheKey(key: string, data: any): string {
    const dataString = JSON.stringify(data)
    return `${key}:${dataString.length}:${Date.now()}`
  }

  /**
   * 计算缓存命中率（简化版本）
   */
  private calculateHitRate(): number {
    // 这里可以实现更复杂的命中率计算逻辑
    // 目前返回一个模拟值
    return 0.85
  }

  /**
   * 发射缓存事件（用于调试和监控）
   */
  private emitCacheEvent(event: string, key: string | null, entry: ModuleCacheEntry | null): void {
    // 这里可以集成到全局事件系统
    if (import.meta.env.DEV) {
      console.debug(`[ModuleStorage] ${event}`, { key, entry })
    }
  }
}

// 创建全局存储实例
export const moduleStorage = new ModuleStorage()
